#include "websocketclient.h"

#include "utils.h"

#include <QtWebSockets/qwebsocket.h>

using namespace std;
using namespace ServerMsgViewer;

WebSocketClient::WebSocketClient()
{
}

WebSocketClient::~WebSocketClient()
{
}

WebSocketClient::WebSocketClientStatus WebSocketClient::openUrl(QString url)
{
    QUrl targetUrl(url);
    if (!targetUrl.isValid()) {
        return ERR_BAD_URL;
    }
    _client = make_unique<QWebSocket>();
    if (!_client) {
        return ERR_CANT_BUILD_WS;
    }
    connect(_client.get(), &QWebSocket::textMessageReceived, this, &WebSocketClient::onMsgRecved);
    connect(_client.get(), &QWebSocket::connected, this, &WebSocketClient::onConnected);
    connect(_client.get(), &QWebSocket::disconnected, this, &WebSocketClient::onDisConnected);
    typedef void (QWebSocket::*sslErrorsSignal)(const QList<QSslError>&);
    connect(_client.get(), static_cast<sslErrorsSignal>(&QWebSocket::sslErrors),
        this, &WebSocketClient::onSslErrors);
    _client->open(targetUrl);
    return OK;
}

WebSocketClient::WebSocketClientStatus WebSocketClient::close()
{
    if (!_client) {
        return ERR_WS_NOT_EXIST;
    }
    _client->abort();
    return OK;
}

WebSocketClient::WebSocketClientStatus WebSocketClient::sendMsg(const QString& msg)
{
    if (!_client) {
        return ERR_NO_ACTIVE_CONNECTION;
    }
    _client->sendTextMessage(msg);
    debug(msg);
    return OK;
}

WebSocketClient::WebSocketClientStatus WebSocketClient::ping()
{
    if (!_client) {
        return ERR_NO_ACTIVE_CONNECTION;
    }
    _client->ping();
    debug("send ping success");
    return OK;
}

void WebSocketClient::onSslErrors(const QList<QSslError>& errors)
{
    Q_UNUSED(errors);
    if (_client) {
        _client->ignoreSslErrors();
    }
}
